<template>
  <div class="wallet-connect">
    <template v-if="web3State.isConnected">
      <div class="wallet-info">
        <div class="wallet-address">
          <span class="label">钱包地址:</span>
          <span class="value">{{ formatAddress(web3State.account) }}</span>
        </div>
        <div class="wallet-balance">
          <span class="label">余额:</span>
          <span class="value">{{ web3State.balance }} {{ getNetworkSymbol() }}</span>
        </div>
        <div class="wallet-network">
          <span class="label">网络:</span>
          <span class="value">{{ web3State.networkName }}</span>
        </div>
      </div>
      <van-button type="danger" size="small" @click="handleDisconnect">断开连接</van-button>
    </template>
    <template v-else>
      <van-button type="primary" @click="handleConnect">连接钱包</van-button>
    </template>
  </div>
</template>

<script setup>
import { onMounted, inject } from 'vue';
import { connectWallet, disconnectWallet, web3State } from '@/utils/web3';
import { showToast } from 'vant';

// 格式化地址，只显示前6位和后4位
const formatAddress = (address) => {
  if (!address) return '';
  return `${address.substring(0, 6)}...${address.substring(address.length - 4)}`;
};

// 获取当前网络的代币符号
const getNetworkSymbol = () => {
  const networks = {
    1: 'ETH',
    56: 'BNB',
    137: 'MATIC',
    42161: 'ETH',
    10: 'ETH',
    // 添加更多网络...
  };
  
  return networks[web3State.chainId] || 'ETH';
};

// 连接钱包
const handleConnect = async () => {
  try {
    await connectWallet();
  } catch (error) {
    showToast('连接钱包失败');
    console.error('连接钱包失败:', error);
  }
};

// 断开钱包连接
const handleDisconnect = () => {
  disconnectWallet();
};
</script>

<style scoped>
.wallet-connect {
  padding: 16px;
  border-radius: 8px;
  background-color: #f5f7fa;
  margin-bottom: 16px;
}

.wallet-info {
  margin-bottom: 12px;
}

.wallet-address,
.wallet-balance,
.wallet-network {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.label {
  color: #666;
}

.value {
  color: #333;
  font-weight: 500;
}
</style>